package com.xinchuang.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.sql.*;

@Slf4j
public class DBUtils {

    public static final String TILE_TEMPLATE = "/templates/template.idb";

    public static void copyFileByTemplate(String templatePath, String path) {
        File target = new File(path);
        if (target.exists()) {
            target.delete();
        }
        copyFileByTemplate(templatePath, target);
    }

    private static void copyFileByTemplate(String templatePath, File target) {
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }
        try (InputStream inputStream = DBUtils.class.getResourceAsStream(templatePath);
             OutputStream outputStream = new FileOutputStream(target)) {
            int temp;
            byte[] data = new byte[1024];
            while ((temp = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, temp);
            }
        } catch (IOException e) {
            log.error("系统异常:", e);
        }
    }

    public static Connection getDbConn(String dbPath) {
        Connection dbConn = null;
        try {
            dbConn = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return dbConn;
    }

    public static void save(String dBPath, byte[] imgBytes, String quadKey) throws SQLException {
        try (Connection dbConn = getDbConn(dBPath);
             PreparedStatement imagesPs = dbConn.prepareStatement("INSERT INTO IMAGES(DATA,KEY) VALUES (?,?)")) {
            imagesPs.setBytes(1, imgBytes);
            imagesPs.setString(2, quadKey);
            imagesPs.executeUpdate();
        } catch (SQLException e) {
            throw e;
        }
    }

    public static byte[] get(String dBPath, String quadKey) {
        byte[] tile = null;
        try (Connection dbConn = getDbConn(dBPath);
             PreparedStatement preparedStatement = dbConn.prepareStatement("SELECT DATA FROM IMAGES WHERE KEY = ?")) {
            preparedStatement.setString(1, quadKey);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    tile = resultSet.getBytes("DATA");
                }
            } catch (SQLException e) {
                throw e;
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return tile;
    }

}
